package com.unibeta.cloudtest.mesher.modules.schedule.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.unibeta.cloudtest.mesher.modules.schedule.repo.JobRepo;
import com.unibeta.cloudtest.mesher.modules.schedule.service.impl.ScheduleJobTask;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.Scheduler;

@Configuration
public class ScheduleConfig {

	@Autowired
	JobRepo jobRepo;
	
	@Bean
	Scheduler scheduler()
	{
		CronUtil.getScheduler().clear();
		
		jobRepo.findAll().stream().filter(j->{
			return j.getStatus();
		}).forEach(j->{
			CronUtil.getScheduler().schedule(j.getName(), j.getCron(), new ScheduleJobTask(j));
		});
		
		if(!CronUtil.getScheduler().isStarted()) {
			CronUtil.getScheduler().start();
		}
		
		return CronUtil.getScheduler();
	}
}
